package com.lmz.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lmz.product.VO.catalog2Vo;
import com.lmz.product.service.CategoryBrandRelationService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmz.common.utils.PageUtils;
import com.lmz.common.utils.Query;

import com.lmz.product.dao.CategoryDao;
import com.lmz.product.entity.CategoryEntity;
import com.lmz.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //组装成父子结构
        //1.找到以及分类
        List<CategoryEntity> level1Menu = entities.stream().filter(CategoryEntity ->
                CategoryEntity.getParentCid() == 0).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 检查是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    //[2，22，123]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //收集节点id
        paths.add(catelogId);
        CategoryEntity item = this.getById(catelogId);
        if (item.getParentCid() != 0) {
            findParentPath(item.getParentCid(), paths);
        }
        return paths;
    }

    /*
     * 更新自己和其他表中关联了的数据
     */
    //@CacheEvict(value = {"category"}, key = "'getLevelOneCategory'") //失效模式--改完删除缓存，保证数据一致性
    @Transactional //标注为事务
    //组合多个操作
    /*@Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'getLevelOneCategory'"),
            @CacheEvict(value = {"category"}, key = "'getCatalgJson'")
    })*/
    //删除某个缓存分区中的所有数据
    @CacheEvict(value = "category",allEntries = true)
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    //获取一级分类
    //@Cacheable 当前方法的结果需要缓存，如果缓存中有直接返回，没有则调用方法再放入缓存,需要指定缓存的分区
    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevelOneCategory() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    //使用SpringCache
    @Cacheable(value = {"category"}, key = "#root.method.name",sync = true) //加锁
    @Override
    public Map<String, List<catalog2Vo>> getCatalgJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有的分类
        //1级
        List<CategoryEntity> levelOneCategory = getParentCid(selectList, 0L);
        //封装数据
        Map<String, List<catalog2Vo>> parent_cid = levelOneCategory.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询每个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());

            List<catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    catalog2Vo catalog2Vo = new catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //封装三级分类
                    List<CategoryEntity> Level3Catalog = getParentCid(selectList, l2.getCatId());
                    if (Level3Catalog != null) {
                        List<catalog2Vo.catalog3Vo> collect = Level3Catalog.stream().map(l3 -> {
                            catalog2Vo.catalog3Vo catalog3Vo = new catalog2Vo.catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return parent_cid;
    }


    //使用redisson加入缓存
    public Map<String, List<catalog2Vo>> getCatalgJsonMyself() {
        /*
        1.空结果缓存解决缓存穿透
        2.添加随机过期时间解决缓存雪崩
        3.加锁解决缓存击穿
         */
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存中没有数据
            Map<String, List<catalog2Vo>> catalgJsonFromDb = getCatalgJsonFromDbWithRedisLock();
            //将结果转为JSON 放入缓存
            //优点：JSON 跨语言跨平台
            return catalgJsonFromDb;
        }
        //类型转换
        Map<String, List<catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<catalog2Vo>>>() {
        });
        return result;
    }

    //三级分类查询--Redisson
    public Map<String, List<catalog2Vo>> getCatalgJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("CatalgJson-lock");
        lock.lock();
        Map<String, List<catalog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    //三级分类查询--分布式锁
    public Map<String, List<catalog2Vo>> getCatalgJsonFromDbWithRedisLock() {
        //防止因业务超时把别人的锁删除了
        String uuidLock = UUID.randomUUID().toString();
        //分布式锁  在redis中占据一个key
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuidLock, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功,执行业务
            //设置过期时间
            Map<String, List<catalog2Vo>> dataFromDb = getDataFromDb();
            //解锁
            //获取值对比和删除指定值也需要是一个原子操作---需要LUA脚本

            String lockValue = redisTemplate.opsForValue().get("lock");
            if (uuidLock.equals(lockValue)) {
                //先判断是不是当前线程自己的锁
                redisTemplate.delete("lock");
            }
            return dataFromDb;
        } else {
            //加锁失败,重试
            //可以休眠一段时间
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {

            }
            return getCatalgJsonFromDbWithLocalLock(); //自旋重试加锁
        }
    }

    //三级分类查询--本地锁
    public Map<String, List<catalog2Vo>> getCatalgJsonFromDbWithLocalLock() {
        synchronized (this) {
            return getDataFromDb();
        }
    }

    //从数据库查询数据
    private Map<String, List<catalog2Vo>> getDataFromDb() {
        //先判断缓存中是否有数据
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<catalog2Vo>>>() {
            });
            return result;
        }

        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有的分类
        //1级
        List<CategoryEntity> levelOneCategory = getParentCid(selectList, 0L);

        Map<String, List<catalog2Vo>> parent_cid = levelOneCategory.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询每个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());

            List<catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    catalog2Vo catalog2Vo = new catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //封装三级分类
                    List<CategoryEntity> Level3Catalog = getParentCid(selectList, l2.getCatId());
                    if (Level3Catalog != null) {
                        List<catalog2Vo.catalog3Vo> collect = Level3Catalog.stream().map(l3 -> {
                            catalog2Vo.catalog3Vo catalog3Vo = new catalog2Vo.catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        String data = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", data, 1, TimeUnit.DAYS);
        return parent_cid;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid().equals(parentCid);
        }).collect(Collectors.toList());
        return collect;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }
}